<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="addRoleVisible = true">添加角色</el-button>
              <!-- 用户列表区域 -->
        <el-table :data="roleList" border stripe>
            <!-- 展开列 -->
          <el-table-column  label="#" type="expand">
            <template slot-scope="scope">
              <el-row :class="['bdBottom','vcenter', i1 === 0 ? 'bdTop' : ''] " v-for="( item1, i1) in scope.row.children" :key="item1.id">
                <!-- 渲染一级权限 -->
                <el-col :span="5">
                  <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二级和三级权限 -->
                <el-col :span="19">
                  <el-row :class="[ i2 === 0 ? '' : 'bdTop','vcenter'] " v-for="(item2, i2) in item1.children" :key="item2.id">
                    <el-col :span="6">
                      <el-tag closable @close="removeRightById(scope.row,item2.id)" type="success">{{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag closable type="warning" v-for="(item3) in item2.children" :key="item3.id" @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column  label="#" type="index"></el-table-column>
            <el-table-column label="角色名称" prop="roleName"></el-table-column>
            <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-row>
                    <el-button type="primary" icon="el-icon-edit" @click="showEditDiolog(scope.row.id)" >编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" @click="deleteRole(scope.row.id)">删除</el-button>
                    <el-button type="warning" icon="el-icon-setting" @click="showSetRightDiolog(scope.row)" >分配权限</el-button>
                </el-row>
              </template>
            </el-table-column>
        </el-table>
        <!-- 添加角色的对话框 -->
        <el-dialog title="添加用户" :visible.sync="addRoleVisible" @close="addDialogClosed"  width="50%" >
           <!-- 内容主体区域 -->
          <el-form label-position="top" :model="addRoleForm" status-icon :rules="addRoleRules" ref="AddRoleFormRef" label-width="70px" class="add_role_form">
            <el-form-item label="角色名称" prop="roleName">
                <el-input  v-model="addRoleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="addRoleForm.roleDesc"></el-input>
            </el-form-item>
            </el-form>
          <span slot="footer" class="dialog-footer">
            <!-- 底部按钮区域 -->
          <el-button @click="addRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 编辑角色的对话框 -->
        <el-dialog title="添加用户" :visible.sync="editRoleVisible" width="50%" @close="editDialogClosed" >
           <!-- 内容主体区域 -->
          <el-form label-position="top" :model="roleInfo" status-icon :rules="addRoleRules" ref="eidtRoleFormRef" label-width="70px" class="add_role_form">
            <el-form-item label="角色名称" prop="roleName">
                <el-input  v-model="roleInfo.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="roleInfo.roleDesc"></el-input>
            </el-form-item>
            </el-form>
          <span slot="footer" class="dialog-footer">
            <!-- 底部按钮区域 -->
          <el-button @click="editRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRole">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 分配权限对话框 -->
        <el-dialog title="分配权限" :visible.sync="setRightdialogVisible" width="30%" @close="setRightdialogColsed">
          <!-- 树形控件 -->
          <el-tree ref="treeRef" :data="rightListTree" :props="treeProps" show-checkbox node-key="id"
          default-expand-all :default-checked-keys="defKeys"></el-tree>
          <span slot="footer" class="dialog-footer">
            <el-button @click="setRightdialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="allotRights">确 定</el-button>
          </span>
        </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      roleList: [],
      addRoleVisible: false,
      editRoleVisible: false,
      setRightdialogVisible: false,
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      roleInfo: {},
      rightListTree: [],
      // 验证角色名称，角色描述规则
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 2 到 6 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { max: 128, message: '不能超过128个字符', trigger: 'blur' }
        ]
      },
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点id值数组
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: ''

    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    async getRoleList () {
      const res = await this.$http.get('roles')
      if (res.data.meta.status !== 200) {
        this.$message.error('获取角色列表失败')
      } else {
        this.roleList = res.data.data
      }
    },
    // 根据id删除权限
    removeRightById (role, rightId) {
      // 弹框提示用户是否删除
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if (res.data.meta.status !== 200) {
          this.$message.error('删除权限失败')
        } else {
          this.$message.success('权限已删除')
          role.children = res.data.data
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 关闭添加角色对话框
    addDialogClosed () {
      this.$refs.AddRoleFormRef.resetFields()
    },
    // 添加角色
    addRole () {
      this.$refs.AddRoleFormRef.validate(async valid => {
        if (!valid) return false
        const res = await this.$http.post('roles', this.addRoleForm)
        if (res.data.meta.status !== 201) {
          this.$message.error('添加角色失败')
        } else {
          this.$message.success('添加成功')
          this.addRoleVisible = false
          this.getRoleList()
        }
      })
    },
    // 删除角色
    deleteRole (id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await this.$http.delete('roles/' + id)
        if (res.data.meta.status !== 200) {
          this.$message.error('删除失败')
        } else {
          this.$message.success('角色已删除')
          this.getRoleList()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 打开编辑对话框并显示数据
    async showEditDiolog (id) {
      this.editRoleVisible = true
      const res = await this.$http.get('roles/' + id)
      if (res.data.meta.status !== 200) {
        this.$message.error('获取角色信息失败')
      } else {
        this.roleInfo = res.data.data
      }
    },
    // 关闭修改对话框事件
    editDialogClosed () {
      this.$refs.eidtRoleFormRef.resetFields()
    },
    // 编辑提交角色
    async editRole () {
      this.$refs.eidtRoleFormRef.validate(async valid => {
        if (!valid) return false
        const res = await this.$http.put('roles/' + this.roleInfo.roleId, {
          roleName: this.roleInfo.roleName,
          roleDesc: this.roleInfo.roleDesc
        })
        if (res.data.meta.status !== 200) {
          this.$message.error('修改角色信息失败')
        } else {
          this.$message.success('修改成功')
          this.editRoleVisible = false
          this.getRoleList()
        }
      })
    },
    // 展示分配权限对话框
    async showSetRightDiolog (role) {
      this.roleId = role.id
      // 获取所有权限数据
      const res = await this.$http.get('rights/tree')
      if (res.data.meta.status !== 200) {
        this.$message.error('获取数据失败')
      } else {
        this.rightListTree = res.data.data
      }
      // 递归获取三级节点id
      this.getLeafKeys(role, this.defKeys)
      this.setRightdialogVisible = true
    },
    // 关闭分配授权对话框
    setRightdialogColsed () {
      this.defKeys = []
    },
    // 通过递归的形式获取角色项下所有的三级权限并保存到defKeys数组中
    getLeafKeys (node, arr) {
      // 如果node节点不包含children属性，说明是三级节点
      if (!node.children) {
        return arr.push(node.id)
      } else {
        node.children.forEach(item =>
          this.getLeafKeys(item, arr))
      }
    },
    // 为角色分配权限
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const res = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: idStr
      })
      if (res.data.meta.status !== 200) {
        this.$message.error('分配权限失败')
      } else {
        this.$message.success('分配权限成功')
        this.getRoleList()
        this.setRightdialogVisible = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
    margin: 7px;
}
.bdTop {
    border-top: 1px solid #eee;
}
.bdBottom {
    border-bottom: 1px solid #eee;
}
.vcenter {
    display: flex;
    align-items: center;
}

</style>
